package uia.alumni.group;

import uia.alumni.profile.*;
import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 * Save the data from the EditProfile form and displa
 * the ViewProfile page.
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class SaveGroup extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.save";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public SaveGroup() {
        super(Role.member);
    }


    /**
     * Save profile data from the EditProfile form.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = getLoggedInUser(em, request);

            String fullname = request.getParameter(FULLNAME);
            if (fullname != null && ! fullname.equals(""))
                user.setFullName(fullname);
            String address = request.getParameter(ADDRESS);
            if (address != null && ! address.equals(""))
                user.setAddress(address);
            String phone = request.getParameter(PHONE);
            if (phone != null && ! phone.equals(""))
                user.setPhone(phone);
            String email = request.getParameter(EMAIL);
            if (email != null && ! email.equals(""))
                user.setUserName(email);
            String description = request.getParameter(DESCRIPTION);
            if (description != null && ! description.equals(""))
                user.setDescription(description);

            tx.commit();
            request.setAttribute(USER, user);
        }
        catch (Exception e) {
            log("Save profile failed", e);
            addMessage(request, "Save profile failed, because"+e.getMessage());
        }
        this.forwardTo(ViewProfile.SERVLET_NAME, request, response);
    }

    public final static long serialVersionUID = 1;

}
